import random

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
import re

from user.models import User
from user.ser import UserSer
from utils import sendcode
from utils.MyJwt import myjwt
from utils.authentication import MyAuthentication, myauthenta
from utils.myredis import myredis
from utils.sendcode import send_message


# Create your views here.
class RegisterView(APIView):
    def post(self, request):
        user = {}
        account = request.data['account']
        password = request.data['password']
        if re.match(r'[a-zA-Z0-9_]{6,14}@(qq|sina|163|139)\.com$', account):
            user['email'] = account
        elif re.match(r'1[3-9]\d{9}$', account):
            for i in User.objects.all():
                if i.phone == account:
                    return Response('注册失败！手机号不能重复注册')
            user['phone'] = account
        else:
            user['username'] = account
        user['password'] = password

        userser = UserSer(data=user)
        if userser.is_valid():
            userser.save()
            return Response('注册成功')
        else:
            return Response(userser.errors)


class LoginByAccount(APIView):
    def post(self, request):
        account = request.data['account']
        password = request.data['password']
        if re.match(r'[a-zA-Z0-9_]{6,14}@(qq|sina|163|139)\.com$', account):
            usermodel = User.objects.filter(email=account)
        elif re.match(r'1[3-9]\d{9}$', account):
            usermodel = User.objects.filter(phone=account)
        else:
            usermodel = User.objects.filter(username=account)

        if usermodel:
            if usermodel[0].password == password:
                token = myjwt.getJwt(account, usermodel[0].id)
                return Response({'msg': '登陆成功', 'token': 'Bearer ' + token, 'id': usermodel[0].id, 'code': 201})
            else:
                return Response({'msg': '用户密码不正确', 'code': 401})
        else:
            return Response({'msg': '用户不存在', 'code': 401})


class LoginByCode(APIView):
    def post(self, request):
        account = request.data['account']
        if re.match('1[3-9]\d{9}$', account):
            code = request.data['code']
            code2 = myredis.getstr(account)
            if code == code2:
                user = User.objects.filter(phone=account)
                if user:
                    tokenjwt = myjwt.getJwt(account, user[0].id)
                    return Response({'msg': '登陆成功', 'token': tokenjwt})
                else:
                    data = {'phone': account, 'password': '000000'}
                    ser = UserSer(data=data)

                    if ser.is_valid():
                        tokenjwt = myjwt.getJwt(account, ser.validated_data.get('id'))
                        ser.save()
                        return Response({'msg': '登陆成功', 'token': tokenjwt, 'userid': ser.data.get('id')})

            else:
                return Response({'msg': '验证码不正确'})
        else:
            return Response({'msg': '手机号验证不通过'})


class SendCode(APIView):
    def post(self, request):
        account = request.data['account']
        ran = random.randint(1000, 9999)
        # if send_message(account, ran):
        myredis.settxt(account, ran, 60 * 2)
        return Response({'msg': '验证码发送成功', 'code': ran})
        # else:
        #     return Response('验证码发送失败')


class Test(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        return Response("546456465")
